
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

void print_usage(int);
void Make_Range();

unsigned char tabflag[65536+4];
FILE * outfile;

int main(int argc, char *argv[])
{
    print_usage(argc);
    outfile = fopen(argv[1], "wt");
    if ( outfile==NULL ) {
        printf("cannot write file : %s\n", outfile);
        return -1;
    }
    Make_Range();
    return 0;
}

void Make_Range()
{
    unsigned code;
    unsigned char pbbuf[4];
    unsigned short pwbuf[4];
    int number;
    unsigned start, end, cnt, exist_flag;

    memset(tabflag, 0, sizeof(tabflag));
    for ( code = 0; code <= 0x80; code++ )
        tabflag[code] = 1;
    for ( code = 0x8100; code < 0xff00; code ++ )
    {
        if ( (code & 0xff) < 0x30 )
            continue;
        pbbuf[0] = (code >> 8) & 0xff;
        pbbuf[1] = code & 0xff;
        pbbuf[2] = 0;
        pbbuf[3] = 0;
        number = MultiByteToWideChar(936, MB_ERR_INVALID_CHARS, pbbuf, strlen(pbbuf), pwbuf, 4);
        if ( number == 0 )
        {
            int error = GetLastError();
            printf("Error : Cannot convert the char=0x%04X to unicode , charset is cp%d\n", code, 936);
            printf("  Windows Error : %d\n", error);
            continue;
        }
        tabflag[code] = 1;
    }
    ////////////////////////////////////////////
    start = 0;
    cnt = 0;
    exist_flag = 1;
    while ( cnt <= 0xffff )
    {
        if ( exist_flag )
        {
            if ( tabflag[cnt+1] == 0 )
            {
                end = cnt;
                if ( start == end )
                    fprintf(outfile, "%04X\n", start);
                else
                    fprintf(outfile, "%04X-%04X\n", start, end);
                exist_flag = 0;
            }
        }
        else
        {
            if ( tabflag[cnt+1] != 0 )
            {
                start = cnt+1;
                exist_flag = 1;
            }
        }
        cnt ++;
    }
}

void print_usage(int argc)
{
    if ( argc <= 1 )
    {
        printf("  usage : \n      gbk_range  output_filename\n");
        printf("\n  Press any to exit. \n");
        getch();
        exit(0);
    }
}
